package org.github.p2w.entity;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;

import java.util.List;

/**
 * url
 *
 * @author xiayongchao
 * @date 2022/08/02
 */
@Data
public class Url {
    private String raw;

    private String protocol;

    private List<String> host;

    private String port;

    private List<String> path;

    private List<Parameter> query;

    /**
     * 获取请求地址
     *
     * @return {@link String}
     */
    public String getRequestAddress() {
        String pathStr = ArrayUtil.join(ArrayUtil.toArray(path, String.class), "/");
        return (StrUtil.isNotBlank(protocol) ? protocol +  "://" : "")
                + host.get(0)
                + (StrUtil.isNotBlank(port) ? ":" + port : "") + "/" + pathStr;
    }

    /**
     * 获取请求参数
     *
     * @return {@link String}
     */
    public String getRequestParams() {
        if (query == null || query.isEmpty()) {
            return "";
        }
        StringBuilder params = new StringBuilder("?");
        query.forEach(parameter -> params.append(parameter.getKey())
                .append("=")
                .append(parameter.getValue())
                .append("&"));
        return params.substring(0, params.length() - 1);
    }

}
